<!-- TEST for least mean square curve fitting -->

<canvas id="toneWindow" width="400px" height="400px"></canvas>
<script type="text/javascript">
		var startTime = new Date().getTime();

		var c = document.getElementById("toneWindow");
		var ctx = c.getContext('2d');

		var tones = [2, 2, 3, 3, 1, 0, 0, 2, 2, 1];

   	var n = tones.length; 
   	var max = 4;
   	var sumXY = 0;
   	var sumX = 0;
   	var sumY = 0;
   	var sumXX = 0;
   	var sumYY = 0;


   	var xy = new Array();

   	for (var i = 0; i < n; i++) {
			ctx.fillText('x', i*c.width/n, c.height - tones[i]*c.height/max);
   		sumX += i;
   		sumY += tones[i];
   		sumXX += i*i;
   		sumYY += tones[i]*tones[i];
   		sumXY += tones[i]*i;
   	};

   	var avgX = sumX/n;
   	var avgY = sumY/n;
   	var avgXY = sumXY/n;
   	var avgXX = sumXX/n;
   	var avgYY = sumYY/n;

   	var varXY = avgXY - avgX*avgY;
   	var varX = avgXX - avgX*avgX;
   	var varY = avgYY - avgY*avgY;

   	var b = varXY/varX;
   	var a = avgY - b*avgX;

 		var start = [0, c.height - a*c.height/max];
 		var stop = [c.width,c.height - (a+b*n)*c.height/max]

  	ctx.moveTo(start[0], start[1]);
    ctx.lineTo(stop[0], stop[1]);

		ctx.stroke();
    


   	var corrCoeff = (varXY*varXY)/(varX*varY);
   	ctx.fillText('r^2: ' + corrCoeff, 10, 20);
   	ctx.fillText('y = ' + a + ' + ' + b + 'x', 10, 40);
	
   	var endTime = new Date().getTime();
   	var totalTime = endTime - startTime;

   	ctx.fillText('Execution time: ' + totalTime + 'ms', 10, 60);
</script>